package com.sk.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class EchoServer {
    private final int port;
    public EchoServer(int port){
        this.port = port;
    }

    public static void main(String [] args) throws Exception{
        new EchoServer(18080).start();
    }

    public void start() throws Exception{
        //
        final EchoServerHandlerIn echoServerHandlerIn = new EchoServerHandlerIn();
        final EchoServerHandlerOut echoServerHandlerOut = new EchoServerHandlerOut();
        //创建EventLoopGroup
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(3);
        //EventLoopGroup oioloopGroup = new OioEventLoopGroup();
        try{
            //创建ServerBootstrap
            ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(eventLoopGroup)
                        .channel(NioServerSocketChannel.class)//指定所使用的NIO传输Channel
                        .localAddress(new InetSocketAddress(this.port))//使用指定的端口设置套接字地址
                        //添加一个EchoServerHandler到子Channel的ChannelPipeline
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch){
                                //EchoServerHandler被标注为@Shareable，所以我们总是可以使用同样的实力
                                ch.pipeline().addLast(echoServerHandlerIn)
                                    .addLast(echoServerHandlerOut);
                            }
                        });
            //异步绑定服务器，并调用sync阻塞等待直到绑定完成。
            ChannelFuture future = serverBootstrap.bind().sync();
            future.addListener(new ChannelFutureListener() {
                @Override public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess()){
                        System.out.println("回调成功了");
                    }else {
                        System.out.println("失败异常了");
                    }
                }
            });
            future.channel().closeFuture().sync();//获取channel的closeFuture，并阻塞当前线程直到它完成。

        }finally {
            //关闭EventLoopGroup，并释放所有资源。
            eventLoopGroup.shutdownGracefully().sync();
        }


    }
}
